<template>
  <div>
    <!-- 面包屑 -->
    <el-breadcrumb>
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片区 -->
    <el-card class="box-card">
      <!-- 对搜索框和按钮使用栅格布局 -->
      <el-row :gutter="20">
        <el-col :span="10">
          <!-- 搜索框 -->
          <el-input
            placeholder="请输入内容"
            clearable
            v-model="qureyInfo.query"
            @clear="getUsers"
          >
            <el-button
              slot="append"
              icon="el-icon-search"
              @click="getUsers"
            ></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="addDialogVisible = true"
            >添加用户</el-button
          >
        </el-col>
      </el-row>
      <!-- 添加用户 对话框 -->
      <el-dialog
        title="添加用户"
        @close="addDialogColosed"
        :visible.sync="addDialogVisible"
        width="50%"
      >
        <!-- 内容主体区域 -->
        <el-form
          :model="addForm"
          :rules="rules"
          ref="addForm"
          label-width="100px"
          class="demo-ruleForm"
        >
          <el-form-item
            label="用户名"
            prop="username"
            v-model="addForm.username"
          >
            <el-input v-model="addForm.username"></el-input>
          </el-form-item>

          <el-form-item label="密码" prop="password" v-model="addForm.password">
            <el-input v-model="addForm.password"></el-input>
          </el-form-item>

          <el-form-item label="邮箱" prop="email" v-model="addForm.email">
            <el-input v-model="addForm.email"></el-input>
          </el-form-item>

          <el-form-item label="手机" prop="mobile" v-model="addForm.mobile">
            <el-input v-model="addForm.mobile"></el-input>
          </el-form-item>
        </el-form>

        <!-- 底部区域 -->
        <span slot="footer" class="dialog-footer">
          <el-button @click="addDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="addUser">确 定</el-button>
        </span>
      </el-dialog>

      <!-- 修改用户 对话框 -->
      <el-dialog
        title="修改用户"
        @close="editDialogClosed"
        :visible.sync="editDialogVisible"
        width="50%"
      >
        <!-- 内容主体区域 -->
        <el-form
          :model="editForm"
          :rules="editRules"
          ref="editForm"
          label-width="100px"
          class="demo-ruleForm"
        >
          <el-form-item label="用户名">
            <el-input v-model="editForm.username" disabled></el-input>
          </el-form-item>
          <el-form-item label="邮箱" v-model="editForm.email">
            <el-input v-model="editForm.email"></el-input>
          </el-form-item>
          <el-form-item label="手机" v-model="editForm.mobile">
            <el-input v-model="editForm.mobile"></el-input>
          </el-form-item>
        </el-form>

        <!-- 底部区域 -->
        <span slot="footer" class="dialog-footer">
          <el-button @click="editDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="editUser(editForm.id)"
            >确 定</el-button
          >
        </span>
      </el-dialog>

      <!-- 用户列表区域 -->
      <el-table :data="userList" style="width: 100%" border stripe>
        <!-- 索引列 -->
        <el-table-column type="index"></el-table-column>

        <el-table-column prop="username" label="用户名" width="180">
        </el-table-column>
        <el-table-column prop="email" label="邮箱" width="180">
        </el-table-column>
        <el-table-column prop="mobile" label="手机号" width="180">
        </el-table-column>
        <el-table-column prop="role_name" label="角色"> </el-table-column>
        <el-table-column prop="mg_state" label="状态">
          <!--slot-scope 作用域插槽  -->
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.mg_state"
              @change="userStateChanged(scope.row)"
            ></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180px">
          <template slot-scope="scope">
            <el-button
              type="primary"
              icon="el-icon-edit"
              circle
              size="mini"
              @click="editDialog(scope.row.id)"
            ></el-button>
            <el-button
              type="danger"
              icon="el-icon-delete"
              circle
              size="mini"
              @click="removeUserById(scope.row.id, scope.row.username)"
            ></el-button>

            <el-tooltip
              class="item"
              effect="dark"
              content="分配角色"
              placement="top"
              :enterable="false"
            >
              <el-button
                type="warning"
                icon="el-icon-setting"
                circle
                size="mini"
                @click="showAllotRoleDialog(scope.row)"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分配角色对话框 -->
      <el-dialog
        title="分配角色"
        :visible.sync="setRoleDialogVisible"
        width="50%"
        @close="closedAllotRoleDialog"
      >
        <p>用户名：{{ currentUser.username }}</p>
        <p>当前角色：{{ currentUser.role_name }}</p>
        <p>分配新角色：</p>
        <el-select v-model="selectRoleId" clearable placeholder="请选择">
          <el-option
            v-for="item in options"
            :key="item.id"
            :label="item.roleName"
            :value="item.id"
          >
          </el-option>
        </el-select>
        <!-- 底部区域 -->
        <span slot="footer" class="dialog-footer">
          <el-button @click="closedAllotRoleDialog">取 消</el-button>
          <el-button type="primary" @click="allotRole">确 定</el-button>
        </span>
      </el-dialog>

      <!-- 分页区域 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="qureyInfo.pagenum"
        :page-sizes="[1, 2, 3, 4]"
        :page-size="100"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </el-card>
  </div>
</template>

<script>
export default {
  created() {
    this.getUsers()
  },
  data() {
    //   自定义校验邮箱规则
    let checkEmail = (rules, value, callback) => {
      const regEmail = /^[a-zA-Z0-9]+([-_.][a-zA-Z0-9]+)*@[a-zA-Z0-9]+([-_.][a-zA-Z0-9]+)*\.[a-z]{2,}$/

      if (regEmail.test(value)) {
        //合法邮箱
        return callback()
      }
      // 非法邮箱
      callback(new Error('请输入合法邮箱'))
    }
    // 自定义校验手机号规则
    let checkMobile = (rules, value, callback) => {
      const regMobile = /^1[3|4|5|7|8][0-9]{9}$/

      if (regMobile.test(value)) {
        return callback()
      }

      callback(new Error('请输入合法的手机号'))
    }

    return {
      qureyInfo: {
        query: '',
        pagenum: 1,
        pagesize: 2,
      },
      userList: [],
      total: 0,
      addDialogVisible: false,
      rules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' },
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          {
            min: 6,
            max: 15,
            message: '长度在 6 到 15 个字符',
            trigger: 'blur',
          },
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' },
        ],
        mobile: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { validator: checkMobile, trigger: 'blur' },
        ],
      },
      editRules: {
        editEmail: [
          { required: false, message: '请输入邮箱', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' },
        ],
        editMobile: [
          { required: false, message: '请输入手机号', trigger: 'blur' },
          { validator: checkMobile, trigger: 'blur' },
        ],
      },
      addForm: {
        username: '',
        password: '',
        email: '',
        mobile: '',
      },
      editForm: {
        email: '',
        mobile: '',
      },
      //控制修改对话框的显示与隐藏
      editDialogVisible: false,
      //控制分配角色对话框的显示与隐藏
      setRoleDialogVisible: false,
      currentUser: {
        username: '',
        role_name: '',
        id: '',
      },
      // 角色选项
      options: [],
      role: '',
      selectRoleId: '',
    }
  },
  methods: {
    async getUsers() {
      const { data: res } = await this.$http.get('users', {
        params: this.qureyInfo,
      })

      if (res.meta.status !== 200)
        return this.$message.error('获取用户列表失败')

      //   console.log(res)
      this.userList = res.data.users
      this.total = res.data.total
    },
    // 监听pagesize改变事件
    handleSizeChange(newSize) {
      this.qureyInfo.pagesize = newSize
      this.getUsers()
      //   console.log(newSize)
    },
    // 监听 页码值改变事件
    handleCurrentChange(currentNum) {
      this.qureyInfo.pagenum = currentNum
      this.getUsers()
      //   console.log('页码值' + currentNum)
    },
    // 监听用户状态改变事件
    async userStateChanged(userInfo) {
      //   console.log(userInfo)
      const { data: res } = await this.$http.put(
        `users/${userInfo.id}/state/${userInfo.mg_state}`
      )

      if (res.meta.status !== 200) {
        //用户状态修改失败 要恢复原状态
        userInfo.mg_state = !userInfo.mg_state
        this.$message.error('状态修改失败！')
      }

      this.$message.success('状态修改成功！')
    },
    // 监听添加用户的对话框事件
    addDialogColosed() {
      //当对话框关闭时 重置表单的验证
      this.$refs.addForm.resetFields()
    },
    // 添加用户
    addUser() {
      // 在正式发起请求之前先预校验
      this.$refs.addForm.validate(async (valid) => {
        //   校验失败
        if (!valid) return this.$message.error('请检查数据填写是否正确')
        // 校验成功 发起添加请求
        const { data: res } = await this.$http.post('users', this.addForm)

        if (res.meta.status !== 201) return this.$message.error('添加失败')

        this.$message.success('添加成功')

        // 成功之后关掉对话框
        this.addDialogVisible = false
        // 刷新用户列表
        this.getUsers()
      })
    },
    //修改对话框
    async editDialog(id) {
      // 发起根据用户id的查询请求
      const { data: res } = await this.$http.get(`users/${id}`)
      // 查询失败
      if (res.meta.status !== 200) return this.$message.error('不存在该用户')
      //查询成功
      //this.$message.success('查询成功')
      // 显示对话框
      this.editDialogVisible = true

      this.editForm = res.data
      //   console.log(id)
    },
    // 修改用户数据
    editUser(id) {
      // 修改数据之前记得预验证下
      this.$refs.editForm.validate(async (valid) => {
        if (!valid) return this.$message.error('请检查数据填写是否正确')
        console.log(this.editForm.email)
        const { data: res } = await this.$http.put(`users/${id}`, {
          email: this.editForm.email,
          mobile: this.editForm.mobile,
        })

        // 修改失败
        if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
        // 修改成功
        this.$message.success(res.meta.msg)
        //更新本地数据
        // this.editForm = res.data
        console.log(this.editForm)
        this.getUsers()
        //关闭修改对话框
        this.editDialogVisible = false
      })
    },
    // 关闭修改对话框重置验证
    editDialogClosed() {
      this.$refs.editForm.resetFields()
    },
    // 删除对话框关闭时触发
    deleteDialogClosed() {
      this.deleteDialogClosed = !this.deleteDialogClosed
    },
    // 删除用户 我们使用MessageBox确认弹框
    async removeUserById(id, username) {
      const confirmResult = await this.$confirm(
        `此操作将永久删除该用户 : ${username}, 是否继续?`,
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
      ).catch((err) => err)
      //如果用户确认删除 返回值为confirm 反之 cancel
      console.log(confirmResult)
      console.log(id)

      if (confirmResult !== 'confirm') {
        return this.$message.info('已取消删除')
      }

      const { data: res } = await this.$http.delete(`users/${id}`)

      if (res.meta.status !== 200) {
        return this.$message.error('删除用户失败')
      }

      this.$message.success('删除用户成功')

      this.getUsers()
    },

    //显示分配角色对话框
    showAllotRoleDialog(row) {
      this.getRoleList()
      this.setRoleDialogVisible = true
      // console.log(row)
      this.currentUser.username = row.username
      this.currentUser.role_name = row.role_name
      this.currentUser.id = row.id

      //console.log(row)
    },
    //分配新角色(更新角色字段)
    async allotRole() {
      this.setRoleDialogVisible = false
      const { data: res } = await this.$http.put(
        `users/${this.currentUser.id}/role/`,
        {
          rid: this.selectRoleId,
        }
      )

      if (res.meta.status !== 200) {
        this.$message.error('分配角色失败')
      }

      this.$message.success('分配角色成功')
      this.getUsers()
    },

    //获取角色列表
    async getRoleList() {
      const { data: res } = await this.$http.get('roles')

      if (res.meta.status !== 200) {
        return this.$message.error('加载角色列表失败')
      }
      console.log(res.data)
      this.options = res.data
    },
    //分配角色对话框取消时关闭并恢复初始状态
    closedAllotRoleDialog() {
      this.setRoleDialogVisible = false
      //恢复初始状态
      this.selectRoleId = ''
      this.options = []
    },
  },
}
</script>

<style lang="less" scoped>
</style>